// 增强肉鸽系统 - 程序化生成与深度循环机制
class RoguelikeEnhanced {
    constructor() {
        this.runCount = 0; // 游戏轮次计数
        this.currentRun = {
            startTime: 0,
            upgradesChosen: [],
            eventsEncountered: [],
            weaponsFound: [],
            totalKills: 0,
            totalDamage: 0,
            levelsCompleted: 0
        };
        
        // 遗产系统
        this.legacyBonuses = this.loadLegacyBonuses();
        
        // 解锁内容系统
        this.unlockedContent = this.loadUnlockedContent();
        
        // 程序化关卡生成器
        this.levelGenerator = new ProceduralLevelGenerator();
        
        // 随机事件系统
        this.eventSystem = new RandomEventSystem();
        
        // 程序化装备系统
        this.equipmentSystem = new ProceduralEquipmentSystem();
        
        this.initializeRun();
    }
    
    // 开始新的游戏轮次
    startNewRun() {
        this.runCount++;
        this.currentRun = {
            startTime: Date.now(),
            upgradesChosen: [],
            eventsEncountered: [],
            weaponsFound: [],
            totalKills: 0,
            totalDamage: 0,
            levelsCompleted: 0,
            runId: this.generateRunId()
        };
        
        // 应用遗产奖励
        this.applyLegacyBonuses();
        
        // 重置临时效果
        if (window.roguelikeSystem) {
            window.roguelikeSystem.resetTemporaryEffects();
        }
        
        console.log(`🎮 开始第 ${this.runCount} 轮游戏`);
        this.saveRunData();
    }
    
    // 玩家死亡处理 - 真正的永久死亡
    handlePlayerDeath() {
        const runData = this.currentRun;
        const deathRewards = this.calculateDeathRewards(runData);
        
        // 保存部分金币作为遗产
        const coinsToKeep = Math.floor(deathRewards.totalCoins * 0.3); // 保留30%金币
        if (window.roguelikeSystem) {
            window.roguelikeSystem.addCurrency(coinsToKeep);
        }
        
        // 添加遗产奖励
        this.addLegacyBonus(runData);
        
        // 解锁新内容
        this.checkUnlocks(runData);
        
        // 显示死亡总结界面
        this.showDeathSummary(runData, deathRewards);
        
        // 更新统计
        this.updateDeathStatistics(runData);
        
        console.log(`💀 第 ${this.runCount} 轮结束，获得遗产奖励:`, deathRewards);
    }
    
    // 计算死亡奖励
    calculateDeathRewards(runData) {
        const baseCoins = 50;
        const killBonus = runData.totalKills * 2;
        const levelBonus = runData.levelsCompleted * 25;
        const timeBonus = Math.floor((Date.now() - runData.startTime) / 1000 / 60) * 5; // 每分钟5金币
        
        return {
            totalCoins: baseCoins + killBonus + levelBonus + timeBonus,
            newUnlocks: [],
            legacyPoints: Math.floor(runData.levelsCompleted / 2) + 1
        };
    }
    
    // 添加遗产奖励
    addLegacyBonus(runData) {
        const bonusType = this.selectLegacyBonusType(runData);
        
        if (!this.legacyBonuses[bonusType]) {
            this.legacyBonuses[bonusType] = 0;
        }
        
        this.legacyBonuses[bonusType]++;
        this.saveLegacyBonuses();
        
        console.log(`🏆 获得遗产奖励: ${bonusType} (等级 ${this.legacyBonuses[bonusType]})`);
    }
    
    // 选择遗产奖励类型
    selectLegacyBonusType(runData) {
        const bonusTypes = ['startingHealth', 'startingAmmo', 'startingSpeed', 'earlyWeapon', 'luckyStart'];
        
        // 根据游戏表现智能选择
        if (runData.totalKills > 50) return 'combatMastery';
        if (runData.levelsCompleted >= 5) return 'survivalInstinct';
        if (runData.weaponsFound.length > 3) return 'weaponExpertise';
        
        // 默认随机选择
        return bonusTypes[Math.floor(Math.random() * bonusTypes.length)];
    }
    
    // 应用遗产奖励到新游戏
    applyLegacyBonuses() {
        Object.entries(this.legacyBonuses).forEach(([bonusType, level]) => {
            if (level > 0) {
                this.applySpecificLegacyBonus(bonusType, level);
            }
        });
    }
    
    applySpecificLegacyBonus(bonusType, level) {
        switch (bonusType) {
            case 'startingHealth':
                if (window.player) {
                    const healthBonus = level * 15;
                    window.player.maxHealth += healthBonus;
                    window.player.health = window.player.maxHealth;
                }
                break;
                
            case 'startingAmmo':
                if (window.player && window.player.currentWeapon) {
                    window.player.currentWeapon.ammo += level * 10;
                    window.player.currentWeapon.totalAmmo += level * 30;
                }
                break;
                
            case 'startingSpeed':
                if (window.player) {
                    window.player.speed *= (1 + level * 0.05);
                }
                break;
                
            case 'earlyWeapon':
                // 在第一关就给予更好的武器
                this.scheduleEarlyWeaponDrop();
                break;
                
            case 'luckyStart':
                // 提高早期道具掉落率
                this.increasedDropRate = 1 + level * 0.2;
                break;
                
            case 'combatMastery':
                if (window.roguelikeSystem) {
                    window.roguelikeSystem.activeEffects.damageMultiplier *= (1 + level * 0.08);
                }
                break;
                
            case 'survivalInstinct':
                if (window.player) {
                    window.player.damageTakenMultiplier = Math.max(0.5, 1 - level * 0.05);
                }
                break;
        }
        
        console.log(`✨ 应用遗产奖励: ${bonusType} 等级 ${level}`);
    }
    
    // 程序化关卡生成增强
    enhanceLevel(levelIndex) {
        const levelData = this.levelGenerator.generateLevelVariant(levelIndex);
        return this.levelGenerator.applyRandomModifiers(levelData);
    }
    
    // 关卡间随机事件
    triggerRandomEvent() {
        if (Math.random() < 0.4) { // 40%概率触发事件
            const event = this.eventSystem.generateRandomEvent();
            this.showEventInterface(event);
            this.currentRun.eventsEncountered.push(event.id);
        }
    }
    
    // 显示事件选择界面
    showEventInterface(event) {
        const eventMenu = document.createElement('div');
        eventMenu.id = 'randomEventMenu';
        eventMenu.className = 'random-event-menu';
        
        eventMenu.innerHTML = `
            <div class="event-overlay">
                <div class="event-container">
                    <div class="event-icon">${event.icon}</div>
                    <h2 class="event-title">${event.title}</h2>
                    <p class="event-description">${event.description}</p>
                    <div class="event-choices">
                        ${event.choices.map((choice, index) => `
                            <button class="event-choice-btn" data-choice="${index}">
                                <div class="choice-title">${choice.title}</div>
                                <div class="choice-description">${choice.description}</div>
                                <div class="choice-reward">${choice.reward}</div>
                            </button>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(eventMenu);
        
        // 添加选择事件监听器
        event.choices.forEach((choice, index) => {
            const button = eventMenu.querySelector(`[data-choice="${index}"]`);
            button.addEventListener('click', () => {
                this.executeEventChoice(event, choice);
                this.closeEventInterface();
            });
        });
        
        this.addEventStyles();
    }
    
    // 执行事件选择
    executeEventChoice(event, choice) {
        try {
            // 执行奖励或惩罚
            choice.effect();
            
            // 记录选择
            this.currentRun.eventsEncountered.push({
                eventId: event.id,
                choice: choice.title,
                timestamp: Date.now()
            });
            
            console.log(`🎲 事件选择: ${event.title} -> ${choice.title}`);
            
        } catch (error) {
            console.error('执行事件选择失败:', error);
        }
    }
    
    closeEventInterface() {
        const eventMenu = document.getElementById('randomEventMenu');
        if (eventMenu) {
            eventMenu.style.animation = 'fadeOut 0.3s ease-out';
            setTimeout(() => {
                if (eventMenu.parentNode) {
                    document.body.removeChild(eventMenu);
                }
            }, 300);
        }
    }
    
    // 显示死亡总结界面
    showDeathSummary(runData, rewards) {
        const summaryMenu = document.createElement('div');
        summaryMenu.id = 'deathSummaryMenu';
        summaryMenu.className = 'death-summary-menu';
        
        const playTime = Math.floor((Date.now() - runData.startTime) / 1000 / 60);
        
        summaryMenu.innerHTML = `
            <div class="death-summary-overlay">
                <div class="death-summary-container">
                    <h2 class="death-title">💀 游戏结束</h2>
                    <div class="run-stats">
                        <h3>第 ${this.runCount} 轮统计</h3>
                        <div class="stat-grid">
                            <div class="stat-item">
                                <span class="stat-label">关卡完成</span>
                                <span class="stat-value">${runData.levelsCompleted}/10</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">敌人击杀</span>
                                <span class="stat-value">${runData.totalKills}</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">游戏时间</span>
                                <span class="stat-value">${playTime}分钟</span>
                            </div>
                            <div class="stat-item">
                                <span class="stat-label">升级选择</span>
                                <span class="stat-value">${runData.upgradesChosen.length}</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="death-rewards">
                        <h3>🏆 遗产奖励</h3>
                        <div class="reward-item">
                            <span class="reward-icon">💰</span>
                            <span class="reward-text">保留金币: ${Math.floor(rewards.totalCoins * 0.3)}</span>
                        </div>
                        <div class="reward-item">
                            <span class="reward-icon">⭐</span>
                            <span class="reward-text">遗产点数: ${rewards.legacyPoints}</span>
                        </div>
                    </div>
                    
                    <div class="death-actions">
                        <button id="restartRunBtn" class="death-action-btn primary">重新开始</button>
                        <button id="legacyShopBtn" class="death-action-btn secondary">遗产商店</button>
                        <button id="statsViewBtn" class="death-action-btn secondary">统计数据</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(summaryMenu);
        
        // 添加按钮事件监听器
        document.getElementById('restartRunBtn').addEventListener('click', () => {
            this.closeSummaryInterface();
            this.startNewRun();
            if (window.game) window.game.startNewGame();
        });
        
        document.getElementById('legacyShopBtn').addEventListener('click', () => {
            this.closeSummaryInterface();
            this.openLegacyShop();
        });
        
        document.getElementById('statsViewBtn').addEventListener('click', () => {
            this.showDetailedStats();
        });
        
        this.addSummaryStyles();
    }
    
    closeSummaryInterface() {
        const summaryMenu = document.getElementById('deathSummaryMenu');
        if (summaryMenu && summaryMenu.parentNode) {
            document.body.removeChild(summaryMenu);
        }
    }
    
    // 生成运行ID
    generateRunId() {
        return 'run_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    
    // 保存/加载数据
    saveRunData() {
        localStorage.setItem('roguelikeEnhanced_currentRun', JSON.stringify(this.currentRun));
        localStorage.setItem('roguelikeEnhanced_runCount', this.runCount.toString());
    }
    
    loadRunData() {
        const saved = localStorage.getItem('roguelikeEnhanced_currentRun');
        if (saved) {
            this.currentRun = JSON.parse(saved);
        }
        
        const runCount = localStorage.getItem('roguelikeEnhanced_runCount');
        if (runCount) {
            this.runCount = parseInt(runCount);
        }
    }
    
    saveLegacyBonuses() {
        localStorage.setItem('roguelikeEnhanced_legacyBonuses', JSON.stringify(this.legacyBonuses));
    }
    
    loadLegacyBonuses() {
        const saved = localStorage.getItem('roguelikeEnhanced_legacyBonuses');
        return saved ? JSON.parse(saved) : {};
    }
    
    saveUnlockedContent() {
        localStorage.setItem('roguelikeEnhanced_unlockedContent', JSON.stringify(this.unlockedContent));
    }
    
    loadUnlockedContent() {
        const saved = localStorage.getItem('roguelikeEnhanced_unlockedContent');
        return saved ? JSON.parse(saved) : {
            weapons: ['pistol'],
            upgrades: [],
            events: [],
            achievements: []
        };
    }
    
    // 初始化运行数据
    initializeRun() {
        this.loadRunData();
        if (!this.currentRun.startTime) {
            this.startNewRun();
        }
    }
    
    // 更新运行统计
    updateRunStats(kills = 0, damage = 0) {
        this.currentRun.totalKills += kills;
        this.currentRun.totalDamage += damage;
        this.saveRunData();
    }
    
    // 记录升级选择
    recordUpgradeChoice(upgradeKey) {
        this.currentRun.upgradesChosen.push({
            upgrade: upgradeKey,
            level: this.currentRun.levelsCompleted,
            timestamp: Date.now()
        });
        this.saveRunData();
    }
    
    // 关卡完成
    completeLevel(levelNumber) {
        this.currentRun.levelsCompleted = Math.max(this.currentRun.levelsCompleted, levelNumber);
        this.saveRunData();
        
        // 触发关卡间事件
        setTimeout(() => {
            this.triggerRandomEvent();
        }, 1000);
    }
    
    addEventStyles() {
        if (document.getElementById('randomEventStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'randomEventStyles';
        styles.textContent = `
            .random-event-menu {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 15000;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .event-overlay {
                position: absolute;
                width: 100%;
                height: 100%;
                background: linear-gradient(135deg, rgba(0, 0, 0, 0.9), rgba(20, 0, 40, 0.9));
                backdrop-filter: blur(10px);
            }
            
            .event-container {
                position: relative;
                z-index: 15001;
                background: linear-gradient(135deg, rgba(30, 30, 30, 0.95), rgba(50, 30, 70, 0.95));
                border: 3px solid #9b59b6;
                border-radius: 20px;
                padding: 40px;
                max-width: 600px;
                text-align: center;
                color: white;
                box-shadow: 0 0 50px rgba(155, 89, 182, 0.3);
            }
            
            .event-icon {
                font-size: 64px;
                margin-bottom: 20px;
            }
            
            .event-title {
                font-size: 28px;
                margin-bottom: 15px;
                color: #e74c3c;
            }
            
            .event-description {
                font-size: 16px;
                line-height: 1.6;
                margin-bottom: 30px;
                color: #ddd;
            }
            
            .event-choices {
                display: flex;
                flex-direction: column;
                gap: 15px;
            }
            
            .event-choice-btn {
                background: linear-gradient(135deg, rgba(40, 40, 40, 0.9), rgba(60, 40, 80, 0.9));
                border: 2px solid #666;
                border-radius: 12px;
                padding: 20px;
                cursor: pointer;
                transition: all 0.3s ease;
                text-align: left;
            }
            
            .event-choice-btn:hover {
                border-color: #9b59b6;
                transform: translateY(-2px);
                box-shadow: 0 5px 20px rgba(155, 89, 182, 0.3);
            }
            
            .choice-title {
                font-size: 18px;
                font-weight: bold;
                color: #fff;
                margin-bottom: 8px;
            }
            
            .choice-description {
                font-size: 14px;
                color: #ccc;
                margin-bottom: 8px;
            }
            
            .choice-reward {
                font-size: 13px;
                color: #00ff88;
                font-weight: bold;
            }
        `;
        
        document.head.appendChild(styles);
    }
    
    addSummaryStyles() {
        if (document.getElementById('deathSummaryStyles')) return;
        
        const styles = document.createElement('style');
        styles.id = 'deathSummaryStyles';
        styles.textContent = `
            .death-summary-menu {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 16000;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .death-summary-overlay {
                position: absolute;
                width: 100%;
                height: 100%;
                background: linear-gradient(135deg, rgba(139, 0, 0, 0.9), rgba(0, 0, 0, 0.95));
                backdrop-filter: blur(15px);
            }
            
            .death-summary-container {
                position: relative;
                z-index: 16001;
                background: linear-gradient(135deg, rgba(40, 40, 40, 0.95), rgba(60, 20, 20, 0.95));
                border: 3px solid #e74c3c;
                border-radius: 25px;
                padding: 50px;
                max-width: 700px;
                text-align: center;
                color: white;
                box-shadow: 0 0 60px rgba(231, 76, 60, 0.5);
            }
            
            .death-title {
                font-size: 36px;
                margin-bottom: 30px;
                color: #e74c3c;
                text-shadow: 0 0 20px rgba(231, 76, 60, 0.8);
            }
            
            .run-stats h3 {
                font-size: 24px;
                margin-bottom: 20px;
                color: #fff;
            }
            
            .stat-grid {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 15px;
                margin-bottom: 30px;
            }
            
            .stat-item {
                background: rgba(0, 0, 0, 0.3);
                padding: 15px;
                border-radius: 10px;
                border: 1px solid #555;
            }
            
            .stat-label {
                display: block;
                font-size: 14px;
                color: #ccc;
                margin-bottom: 5px;
            }
            
            .stat-value {
                display: block;
                font-size: 20px;
                font-weight: bold;
                color: #fff;
            }
            
            .death-rewards h3 {
                font-size: 22px;
                margin-bottom: 20px;
                color: #ffd700;
            }
            
            .reward-item {
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 10px;
                font-size: 16px;
            }
            
            .reward-icon {
                margin-right: 10px;
                font-size: 20px;
            }
            
            .death-actions {
                display: flex;
                gap: 15px;
                justify-content: center;
                margin-top: 30px;
            }
            
            .death-action-btn {
                padding: 15px 25px;
                border: none;
                border-radius: 10px;
                font-size: 16px;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
                text-transform: uppercase;
            }
            
            .death-action-btn.primary {
                background: linear-gradient(135deg, #e74c3c, #c0392b);
                color: white;
            }
            
            .death-action-btn.secondary {
                background: linear-gradient(135deg, #34495e, #2c3e50);
                color: white;
            }
            
            .death-action-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            }
        `;
        
        document.head.appendChild(styles);
    }
}

// 程序化关卡生成器
class ProceduralLevelGenerator {
    constructor() {
        this.levelModifiers = [
            { name: 'denseSwarm', description: '密集群体', effect: { zombieCount: 1.5, spawnRate: 1.3 } },
            { name: 'eliteForces', description: '精英部队', effect: { zombieHealth: 1.4, zombieSpeed: 1.2 } },
            { name: 'ammunition', description: '弹药丰富', effect: { ammoDropRate: 2.0 } },
            { name: 'timeAttack', description: '时间紧迫', effect: { timeLimit: 0.8, scoreMultiplier: 1.5 } },
            { name: 'darkMode', description: '黑暗模式', effect: { visibility: 0.7, zombieSpeed: 0.9 } },
            { name: 'berserk', description: '狂暴模式', effect: { playerSpeed: 1.3, playerDamage: 1.2, zombieDamage: 1.3 } }
        ];
    }
    
    generateLevelVariant(levelIndex) {
        const baseLevelData = this.getBaseLevelData(levelIndex);
        
        // 添加随机变化
        const variant = {
            ...baseLevelData,
            variant: this.generateVariantName(),
            modifiers: [],
            proceduralElements: this.generateProceduralElements(levelIndex)
        };
        
        return variant;
    }
    
    applyRandomModifiers(levelData) {
        const numModifiers = Math.random() < 0.3 ? 2 : 1; // 30%概率应用两个修饰符
        
        for (let i = 0; i < numModifiers; i++) {
            const modifier = this.levelModifiers[Math.floor(Math.random() * this.levelModifiers.length)];
            if (!levelData.modifiers.find(m => m.name === modifier.name)) {
                levelData.modifiers.push(modifier);
            }
        }
        
        return levelData;
    }
    
    generateProceduralElements(levelIndex) {
        return {
            spawnPoints: this.generateSpawnPoints(levelIndex),
            itemLocations: this.generateItemLocations(levelIndex),
            obstacles: this.generateObstacles(levelIndex),
            specialZones: this.generateSpecialZones(levelIndex)
        };
    }
    
    generateSpawnPoints(levelIndex) {
        const baseCount = 3 + levelIndex;
        const spawnPoints = [];
        
        for (let i = 0; i < baseCount; i++) {
            spawnPoints.push({
                x: Math.random() * 900 + 50,
                y: Math.random() * 650 + 50,
                priority: Math.random(),
                zombieType: this.selectRandomZombieType(levelIndex)
            });
        }
        
        return spawnPoints;
    }
    
    generateItemLocations(levelIndex) {
        const itemCount = 2 + Math.floor(levelIndex / 2);
        const items = [];
        
        for (let i = 0; i < itemCount; i++) {
            items.push({
                x: Math.random() * 900 + 50,
                y: Math.random() * 650 + 50,
                type: this.selectRandomItemType(),
                rarity: this.selectItemRarity()
            });
        }
        
        return items;
    }
    
    generateObstacles(levelIndex) {
        const obstacleCount = Math.floor(Math.random() * 5) + 2;
        const obstacles = [];
        
        for (let i = 0; i < obstacleCount; i++) {
            obstacles.push({
                x: Math.random() * 800 + 100,
                y: Math.random() * 550 + 100,
                width: 30 + Math.random() * 70,
                height: 30 + Math.random() * 70,
                type: 'destructible'
            });
        }
        
        return obstacles;
    }
    
    generateSpecialZones(levelIndex) {
        const zones = [];
        
        if (Math.random() < 0.4) { // 40%概率生成特殊区域
            zones.push({
                x: Math.random() * 600 + 200,
                y: Math.random() * 400 + 175,
                radius: 80 + Math.random() * 40,
                type: Math.random() < 0.5 ? 'healing' : 'damage_boost',
                duration: 10000 + Math.random() * 10000
            });
        }
        
        return zones;
    }
    
    selectRandomZombieType(levelIndex) {
        const types = ['normal', 'fast'];
        
        if (levelIndex >= 3) types.push('spitter');
        if (levelIndex >= 5) types.push('tank');
        if (levelIndex >= 7) types.push('explosive');
        
        return types[Math.floor(Math.random() * types.length)];
    }
    
    selectRandomItemType() {
        const types = ['ammo', 'health', 'weapon', 'powerup'];
        return types[Math.floor(Math.random() * types.length)];
    }
    
    selectItemRarity() {
        const rand = Math.random();
        if (rand < 0.05) return 'legendary';
        if (rand < 0.15) return 'epic';
        if (rand < 0.35) return 'rare';
        return 'common';
    }
    
    generateVariantName() {
        const prefixes = ['血腥', '黑暗', '混乱', '死寂', '狂乱', '诡异'];
        const suffixes = ['之夜', '危机', '末日', '梦魇', '试炼', '挑战'];
        
        const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
        const suffix = suffixes[Math.floor(Math.random() * suffixes.length)];
        
        return prefix + suffix;
    }
    
    getBaseLevelData(levelIndex) {
        // 这里应该返回基础关卡数据
        // 为了简化，我们返回一个基础结构
        return {
            level: levelIndex + 1,
            zombieCount: 5 + levelIndex * 3,
            timeLimit: 120000 + levelIndex * 30000
        };
    }
}

// 随机事件系统
class RandomEventSystem {
    constructor() {
        this.events = this.createEventDefinitions();
    }
    
    createEventDefinitions() {
        return [
            {
                id: 'mysteriousTrader',
                title: '神秘商人',
                icon: '🧙‍♂️',
                description: '一个神秘的商人出现在你面前，提供特殊的交易...',
                choices: [
                    {
                        title: '购买强化武器',
                        description: '花费50金币获得强化武器',
                        reward: '武器伤害+50%',
                        effect: () => {
                            if (window.roguelikeSystem && window.roguelikeSystem.spendCurrency(50)) {
                                window.roguelikeSystem.activeEffects.damageMultiplier *= 1.5;
                                window.roguelikeSystem.applyPlayerUpgrades();
                            }
                        }
                    },
                    {
                        title: '购买治疗药水',
                        description: '花费30金币完全回复生命',
                        reward: '生命值全满',
                        effect: () => {
                            if (window.roguelikeSystem && window.roguelikeSystem.spendCurrency(30)) {
                                if (window.player) {
                                    window.player.health = window.player.maxHealth;
                                    window.player.updateHealthUI();
                                }
                            }
                        }
                    },
                    {
                        title: '离开',
                        description: '什么都不买，直接离开',
                        reward: '无',
                        effect: () => {
                            console.log('离开神秘商人');
                        }
                    }
                ]
            },
            
            {
                id: 'abandonedWeaponCache',
                title: '遗弃武器库',
                icon: '📦',
                description: '你发现了一个遗弃的武器箱，但它看起来有些可疑...',
                choices: [
                    {
                        title: '小心打开',
                        description: '谨慎地打开箱子',
                        reward: '安全获得武器',
                        effect: () => {
                            // 安全获得普通武器
                            if (window.roguelikeSystem) {
                                window.roguelikeSystem.addCurrency(20);
                            }
                        }
                    },
                    {
                        title: '强行破坏',
                        description: '用暴力方式打开',
                        reward: '可能获得更好的奖励，但有风险',
                        effect: () => {
                            if (Math.random() < 0.6) {
                                // 60%成功，获得大量金币
                                if (window.roguelikeSystem) {
                                    window.roguelikeSystem.addCurrency(80);
                                }
                            } else {
                                // 40%失败，受到伤害
                                if (window.player) {
                                    window.player.takeDamage(20);
                                }
                            }
                        }
                    },
                    {
                        title: '忽略',
                        description: '太危险了，还是算了',
                        reward: '安全但无收获',
                        effect: () => {
                            console.log('忽略武器箱');
                        }
                    }
                ]
            },
            
            {
                id: 'strangeExperiment',
                title: '奇怪的实验',
                icon: '🧪',
                description: '你在实验室发现了一个正在进行的实验装置...',
                choices: [
                    {
                        title: '注射药剂',
                        description: '注射未知的增强药剂',
                        reward: '随机获得强大增益或负面效果',
                        effect: () => {
                            if (Math.random() < 0.5) {
                                // 正面效果
                                if (window.roguelikeSystem) {
                                    window.roguelikeSystem.activeEffects.speedMultiplier *= 1.3;
                                    window.roguelikeSystem.activeEffects.damageMultiplier *= 1.2;
                                    window.roguelikeSystem.applyPlayerUpgrades();
                                }
                            } else {
                                // 负面效果
                                if (window.player) {
                                    window.player.maxHealth = Math.floor(window.player.maxHealth * 0.8);
                                    window.player.health = Math.min(window.player.health, window.player.maxHealth);
                                    window.player.updateHealthUI();
                                }
                            }
                        }
                    },
                    {
                        title: '销毁实验',
                        description: '破坏实验装置',
                        reward: '获得金币奖励',
                        effect: () => {
                            if (window.roguelikeSystem) {
                                window.roguelikeSystem.addCurrency(40);
                            }
                        }
                    }
                ]
            }
        ];
    }
    
    generateRandomEvent() {
        return this.events[Math.floor(Math.random() * this.events.length)];
    }
}

// 程序化装备系统
class ProceduralEquipmentSystem {
    constructor() {
        this.weaponPrefixes = ['锋利的', '强化的', '诅咒的', '祝福的', '破旧的', '精制的'];
        this.weaponSuffixes = ['毁灭', '速射', '穿透', '爆破', '冰冻', '燃烧'];
        this.rarityColors = {
            common: '#ffffff',
            rare: '#3498db',
            epic: '#9b59b6',
            legendary: '#f39c12'
        };
    }
    
    generateRandomWeapon(baseWeapon, rarity = 'common') {
        const weapon = {
            ...baseWeapon,
            name: this.generateWeaponName(baseWeapon.name, rarity),
            rarity: rarity,
            modifiers: this.generateWeaponModifiers(rarity),
            specialEffects: this.generateSpecialEffects(rarity)
        };
        
        // 应用修饰符
        this.applyModifiers(weapon);
        
        return weapon;
    }
    
    generateWeaponName(baseName, rarity) {
        if (rarity === 'common') return baseName;
        
        const prefix = this.weaponPrefixes[Math.floor(Math.random() * this.weaponPrefixes.length)];
        const suffix = rarity === 'legendary' ? 
            this.weaponSuffixes[Math.floor(Math.random() * this.weaponSuffixes.length)] : '';
            
        return suffix ? `${prefix}${baseName}·${suffix}` : `${prefix}${baseName}`;
    }
    
    generateWeaponModifiers(rarity) {
        const modifiers = {};
        const modifierCount = { common: 0, rare: 1, epic: 2, legendary: 3 }[rarity];
        
        const possibleModifiers = [
            'damage', 'fireRate', 'accuracy', 'ammoCapacity', 'reloadSpeed'
        ];
        
        for (let i = 0; i < modifierCount; i++) {
            const modifier = possibleModifiers[Math.floor(Math.random() * possibleModifiers.length)];
            if (!modifiers[modifier]) {
                modifiers[modifier] = this.getModifierValue(modifier, rarity);
            }
        }
        
        return modifiers;
    }
    
    getModifierValue(modifier, rarity) {
        const multiplier = { common: 1, rare: 1.2, epic: 1.5, legendary: 2 }[rarity];
        
        switch (modifier) {
            case 'damage': return 0.1 + Math.random() * 0.3 * multiplier;
            case 'fireRate': return 0.05 + Math.random() * 0.2 * multiplier;
            case 'accuracy': return 0.05 + Math.random() * 0.15 * multiplier;
            case 'ammoCapacity': return Math.floor((5 + Math.random() * 15) * multiplier);
            case 'reloadSpeed': return 0.1 + Math.random() * 0.2 * multiplier;
            default: return 0;
        }
    }
    
    generateSpecialEffects(rarity) {
        const effects = [];
        
        if (rarity === 'epic' && Math.random() < 0.6) {
            effects.push(this.getRandomSpecialEffect());
        }
        
        if (rarity === 'legendary') {
            effects.push(this.getRandomSpecialEffect());
            if (Math.random() < 0.5) {
                effects.push(this.getRandomSpecialEffect());
            }
        }
        
        return effects;
    }
    
    getRandomSpecialEffect() {
        const effects = [
            { name: 'explosive', description: '子弹爆炸' },
            { name: 'piercing', description: '穿透射击' },
            { name: 'lifesteal', description: '生命偷取' },
            { name: 'freeze', description: '冰冻敌人' },
            { name: 'poison', description: '毒性伤害' }
        ];
        
        return effects[Math.floor(Math.random() * effects.length)];
    }
    
    applyModifiers(weapon) {
        Object.entries(weapon.modifiers || {}).forEach(([modifier, value]) => {
            switch (modifier) {
                case 'damage':
                    weapon.damage = Math.floor(weapon.damage * (1 + value));
                    break;
                case 'fireRate':
                    weapon.fireRate = Math.max(100, weapon.fireRate - weapon.fireRate * value);
                    break;
                case 'ammoCapacity':
                    weapon.ammo += value;
                    weapon.maxAmmo += value;
                    break;
            }
        });
    }
}

// 全局实例
window.roguelikeEnhanced = new RoguelikeEnhanced();

console.log('增强肉鸽系统已加载');